﻿using System;
using System.Linq;
using System.Web;
using System.Web.Security;
using Common.Extensions;
using Common.Modules;
using EYCmsAdmin.Domain.IDomainServices;
using EYCmsAdmin.Domain.Models;
using EYCmsAdmin.Presentation.IPresentationServices;
using EYCmsAdmin.Presentation.Models.LoginModels;
using EYCmsAdmin.Presentation.Models.UserModels;

namespace EYCmsAdmin.Presentation.PresentationServices
{
    public class AccountPresentationService : IAccountPresentationService
    {
        private readonly IUserDomainService userDomainService;

        public AccountPresentationService(IUserDomainService userDomainService)
        {
            this.userDomainService = userDomainService;
        }

        public SuccessLoginModel LogOn(LoginModel model)
        {
            string login = model.UserName.CreateHash();
            User user = userDomainService.GetUserByLogin(login);
            string salt = user.PasswordSalt;
            string password = Security.CreateHashedPassword(model.Password, salt);
            if(user.Password.Equals(password))
            {
                string role = user.Roles.Count == 0 ? string.Empty : user.Roles.First().Name;
                RegisterAuthCookie(user.Id, user.Login, false, role, model.RememberMe);
                return new SuccessLoginModel(user);
            }

            return null;
        }

        private void RegisterAuthCookie(long id, string name, bool writeAccess, string role, bool rememberMe)
        {
            var ticket = new FormsAuthenticationTicket(1, id + "/" + name + "/" + writeAccess, DateTime.Now, rememberMe ? DateTime.Now.AddYears(20) : DateTime.Now.AddHours(1), rememberMe, role, FormsAuthentication.FormsCookiePath);
            var hashCookies = FormsAuthentication.Encrypt(ticket);
            var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashCookies) { Expires = DateTime.Now.AddYears(20), HttpOnly = true };
            HttpContext.Current.Response.Cookies.Add(cookie);
        }
    }
}